package com.pengli.mytools;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.multidex.MultiDexApplication;

import com.pengli.mytools.greendao.CitiesDao;
import com.pengli.mytools.greendao.DaoSession;
import com.pengli.mytools.greendao.GreenDaoDBController;
import com.pengli.mytools.greendao.URLDataDao;
import com.pengli.mytools.retrofit.NetConstant;
import com.pengli.mytools.retrofit.apiService.BaseApiService;
import com.pengli.mytools.retrofit.apiService.BaiduYunApiService;
import com.pengli.mytools.retrofit.apiService.BaiduYunTokenService;
import com.pengli.mytools.retrofit.ServiceGenerator;
import com.pengli.mytools.retrofit.apiService.FileService;
import com.pgyer.pgyersdk.PgyerSDKManager;
import com.pgyer.pgyersdk.pgyerenum.Features;

import org.greenrobot.greendao.database.Database;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;


public class MyApplication extends MultiDexApplication {
    private static MyApplication instance;
    private List<Activity> activitys = new LinkedList<Activity>();
    private DaoSession daoSession;
    private BaseApiService baseApiService;
    private BaiduYunTokenService baiduYunTokenService;
    private BaiduYunApiService baiduYunApiService;
    private FileService fileService;
    private String access_token = "";
    private Context context;
    private SharedPreferences pre;

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    /**
     * 单例模式中获取唯一的MyApplication实例
     */
    public static MyApplication getInstance() {
        if (null == instance) {
            instance = new MyApplication();
        }
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        context=getApplicationContext();

        initSharedPreferences();

        initGreenDao();//初始化greendao

        initTable();//根据sql初始化基础数据

        initRetrofit();
        initPgyerSDK(instance);
    }


    /**
     *  初始化蒲公英SDK
     * @param application
     */
    private static void initPgyerSDK( MyApplication application){
        new PgyerSDKManager.Init()
                .setContext(application) //设置上下问对象
                .enable(Features.CHECK_UPDATE)//开启自动更新
                .start();
    }

    private void initSharedPreferences() {
        pre = context.getSharedPreferences("applicationSharedPreferences",Context.MODE_PRIVATE);
    }

    private void initRetrofit() {
//        baseApiService = ServiceGenerator.createService(BaseApiService.class);
        ServiceGenerator.changeApiBaseUrl(NetConstant.tokenBaseUrl);
        baiduYunTokenService = ServiceGenerator.createService(BaiduYunTokenService.class);
        ServiceGenerator.changeApiBaseUrl(NetConstant.baiduYunBaseUrl);
        baiduYunApiService = ServiceGenerator.createService(BaiduYunApiService.class);
        ServiceGenerator.changeApiBaseUrl(NetConstant.fileDownloadBaseUrl);
        fileService = ServiceGenerator.createService(FileService.class);
    }

    public FileService getFileService() {
        return fileService;
    }

    private void initGreenDao() {
        GreenDaoDBController.initGreenDao();
        daoSession = GreenDaoDBController.getDaoSession();
    }

    private void initTable() {
        boolean flag = pre.getBoolean("flag", false);
        if(flag == false) {//只运行一次
            initTableByAssetsSQLFile("cities.sql");
            initTableByAssetsSQLFile("url.sql");
            pre.edit().putBoolean("flag",true);
        }
    }



    private void initTableByAssetsSQLFile(String sqlFileName) {
        Database database = GreenDaoDBController.getDatabase();
        switch (sqlFileName) {
            case "cities.sql":
                CitiesDao citiesDao = daoSession.getCitiesDao();
                citiesDao.dropTable(database, true);
                citiesDao.createTable(database, true);
                break;
            case "url.sql":
                URLDataDao urlDataDao = daoSession.getURLDataDao();
                urlDataDao.dropTable(database, true);
                urlDataDao.createTable(database, true);
                break;
            default:
        }
        try {
            //读取sql文件
            InputStream open = getInstance().getResources().getAssets().open(sqlFileName);
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String sql = stringBuilder.toString();
            String[] splitSql = sql.split(";");//sql语句分号隔开，SQLlite不支持执行多条sql
            for (String s : splitSql) {
                GreenDaoDBController.excuteSql(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public BaseApiService getBaseApiService() {
        return baseApiService;
    }

    public BaiduYunTokenService getBaiduYunTokenService() {
        return baiduYunTokenService;
    }

    public BaiduYunApiService getBaiduYunApiService() {
        return baiduYunApiService;
    }

    public SharedPreferences getPre() {
        return pre;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activitys != null && activitys.size() >= 0) {
            activitys.add(activity);
        }
    }

    public void removelastActivity() {
        if (activitys != null && activitys.size() > 0) {
            activitys.remove(activitys.size() - 1);
        }
    }

    public Activity getlastActivity() {
        if (activitys.size() >= 1) {
            return activitys.get(activitys.size() - 1);
        } else {
            return null;
        }
    }

    // 遍历所有Activity并finish
    public void exit() {
        if (activitys != null && activitys.size() > 0) {
            for (Activity activity : activitys) {
                activity.finish();
            }
            activitys.clear();
        }
    }

}
